package tech.minesoft.controller;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import tech.minesoft.utils.ObjHolder;
import tech.minesoft.utils.SystemUtils;
import tech.minesoft.vo.DoubanBookVo;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

// TODO 将几个数字参数都调整为 TextField
public class DoubanBookController implements Initializable {
    public TableView<DoubanBookVo> doubanResult;

    private final static String URL_PREFIX = "https://book.douban.com/latest?subcat=%E5%85%A8%E9%83%A8&p=";

    private List<DoubanBookVo> doubanBookVoList = new ArrayList<>();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        doubanResult.setRowFactory(doubanBookVoTableView -> {
            TableRow<DoubanBookVo> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (!row.isEmpty())) {
                    DoubanBookVo rowData = row.getItem();
                    SystemUtils.openBrowser(rowData.getLink());
                }
            });
            return row;
        });
    }

    public void scrapy(ActionEvent actionEvent) {
        Task task = new Task<Void>() {
            @Override
            public Void call() {
                doubanBookVoList.clear();

                for (int i = 1; i <= 3; i++) {
                    String text = "读取页码：" + i;
                    Platform.runLater(() -> {
                        ObjHolder.globalLabel.setText(text);
                    });
                    page(i);
                }

                ObservableList<DoubanBookVo> bookObservableList = FXCollections.observableArrayList(doubanBookVoList);
                doubanResult.setItems(bookObservableList);
                return null;
            }
        };
        new Thread(task).start();
    }

    public void page(int index) {
        try {
            Document document = Jsoup.connect(URL_PREFIX + index).get();

            Elements media = document.select(".media .media__body");

            for (Element element : media) {
                Elements spans = element.select("span");
                String star = spans.get(1).text();

                if (toNumber(star) >= 8) {
                    String people = spans.get(2).text();

                    people = people.replace("(", "").replace("人评价)", "");
                    if (toNumber(people) >= 100) {
                        Elements book = element.select("h2 a");
                        String bookName = book.text();
                        String bookLink = book.attr("href");

                        DoubanBookVo bookVo = new DoubanBookVo();
                        bookVo.setIndex(index);
                        bookVo.setBookName(bookName);
                        bookVo.setStar(star);
                        bookVo.setPeople(people);
                        bookVo.setLink(bookLink);

                        doubanBookVoList.add(bookVo);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public float toNumber(String number) {
        try {
            return Float.parseFloat(number);
        } catch (Exception e) {
            return 0;
        }
    }
}
